/*
 * Copyright (C) 2010 ZXing authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package net.shenru.zxing;

import java.util.Map;

import net.shenru.R;
import net.shenru.ui.zxing.CaptureActivity;
import net.sourceforge.zbar.Config;
import net.sourceforge.zbar.Image;
import net.sourceforge.zbar.ImageScanner;
import net.sourceforge.zbar.Symbol;
import net.sourceforge.zbar.SymbolSet;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.ReaderException;
import com.google.zxing.Result;
import com.google.zxing.ResultPoint;
import com.google.zxing.common.HybridBinarizer;

public final class DecodeHandler extends Handler {

	private static final String TAG = DecodeHandler.class.getSimpleName();

	private final CaptureActivity activity;
	private final MultiFormatReader multiFormatReader;
	private boolean running = true;

	private boolean swap = true;

	private ImageScanner scanner;

	static {
		System.loadLibrary("iconv");
	}

	DecodeHandler(CaptureActivity activity, Map<DecodeHintType, Object> hints) {
		multiFormatReader = new MultiFormatReader();
		multiFormatReader.setHints(hints);
		this.activity = activity;
		scanner = new ImageScanner();
		scanner.setConfig(0, Config.X_DENSITY, 3);
		scanner.setConfig(0, Config.Y_DENSITY, 3);
	}

	@Override
	public void handleMessage(Message message) {
		if (!running) {
			return;
		}
		switch (message.what) {
		case R.id.decode: // 这里的使用了消息循环机制.
			decode((byte[]) message.obj, message.arg1, message.arg2);
			break;
		case R.id.quit: // 这里就是退出扫描线程
			running = false;
			// Looper looper = Looper.myLooper();
			// Looper mainLooper = Looper.getMainLooper();
			// Log.i(TAG,"sub looper:" + looper);
			// Log.i(TAG,"main looper:" + mainLooper);
			// looper.quit();
			Looper.myLooper().quit(); // ---这里看不懂
			break;
		}
	}

	/**
	 * Decode the data within the viewfinder rectangle, and time how long it
	 * took. For efficiency, reuse the same reader objects from one decode to
	 * the next.
	 * 
	 * @param data
	 *            The YUV preview frame.
	 * @param width
	 *            The width of the preview frame.
	 * @param height
	 *            The height of the preview frame.
	 */
	private void decode(byte[] data, int width, int height) {
		long start = System.currentTimeMillis();
		Result rawResult = null;

		PlanarYUVLuminanceSource source = activity.getCameraManager().buildLuminanceSource(data, width, height);
		if (swap) {
			if (source != null) {
				BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
				try {
					Result r = multiFormatReader.decodeWithState(bitmap);
					if (r != null) {
						rawResult = new Result(r.getText() + "--zxing", r.getRawBytes(), r.getResultPoints(),
								r.getBarcodeFormat(), r.getTimestamp());
					}
				} catch (ReaderException re) {
					// continue
				} finally {
					multiFormatReader.reset();
				}
			}
		} else {
			Image image = new Image(width, height, "NV21");
			image.setData(data);
			image = image.convert("Y800");
			int result = scanner.scanImage(image);
			
			if (result != 0) {
				SymbolSet syms = scanner.getResults();
				String strResult = null;
				byte[] dataResult = null;
				for (Symbol sym : syms) {
					strResult = sym.getData();
					dataResult = sym.getDataBytes();
				}
				ResultPoint[] points = new ResultPoint[1];
				ResultPoint point = new ResultPoint(89, 89);
				points[0] = point;
				rawResult = new Result(strResult + "--zbar", dataResult, points, BarcodeFormat.QR_CODE,
						System.currentTimeMillis());
			}
		}
		swap = !swap;

		Handler handler = activity.getHandler();
		if (rawResult != null) {
			// Don't log the barcode contents for security.
			long end = System.currentTimeMillis();
			Log.d(TAG, "Found barcode in " + (end - start) + " ms");
			if (handler != null) {
				Message message = Message.obtain(handler, R.id.decode_succeeded, rawResult);
				Bundle bundle = new Bundle();
				bundle.putParcelable(DecodeThread.BARCODE_BITMAP, source.renderCroppedGreyscaleBitmap());
				message.setData(bundle);
				message.sendToTarget();
			}
		} else {
			if (handler != null) {
				Message message = Message.obtain(handler, R.id.decode_failed);
				message.sendToTarget();
			}
		}
	}

}
